package com.starbaba.system.role.view;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.util.Assert;

import com.opensymphony.xwork2.Action;
import com.starbaba.core.utils.PkUtils;
import com.starbaba.core.utils.PropertyParamMapBuilder;
import com.starbaba.core.utils.Struts2Utils;
import com.starbaba.core.utils.json.JsonUtils;
import com.starbaba.core.web.constant.Constants;
import com.starbaba.core.web.struts2.BaseAction;
import com.starbaba.core.web.struts2.JsonResult;
import com.starbaba.core.web.tree.TreeBuilder;
import com.starbaba.core.web.tree.TreeNode;
import com.starbaba.system.menu.model.MenuVO;
import com.starbaba.system.role.model.RoleVO;
import com.starbaba.system.roleofmenu.dao.QueryRoleOfMenuStrategy;
import com.starbaba.system.roleofmenu.dao.SaveRoleOfMenuStrategy;


@SuppressWarnings("serial")
public class RoleAction extends BaseAction {	
	
	public RoleAction() {
		this.voClass = RoleVO.class;
		this.pkNameArray = new String[]{"roleid"};
		this.setSaveLog(false);
	}
	
	@SuppressWarnings("rawtypes")
    @Override
	public void beforeSave() throws Exception {
		Long curMaxRoleId = (Long) this.getService().doFindMaxPropertyValle(voClass, "roleid");
		if(curMaxRoleId == null){
			curMaxRoleId = Long.parseLong(Constants.ROLE_ID_START_VALUE);
		}
		Long nextRoleId = curMaxRoleId + 1;
		((RoleVO)this.entityVO).setRoleid(nextRoleId);
		((RoleVO)this.entityVO).setComid(userVO.getComid());
		((RoleVO)this.entityVO).setCreator(userVO.getUserid());
		((RoleVO)this.entityVO).setCreatetime(new Date());
		this.setSaveLog(false);
		RoleVO vo = (RoleVO)this.getEntityVO();
		ArrayList list =(ArrayList)this.getService().doFindByProperty(RoleVO.class, "rolename", vo.getRolename());
		
		if(null != list && list.size()> 0){
			throw new Exception("角色名称已经存在");
		};
	}
	
    @Override
    @SuppressWarnings("rawtypes")
	protected void beforeUpdate() throws Exception {
		RoleVO vo = (RoleVO)this.getEntityVO();
		RoleVO oldVO = (RoleVO)this.getService().doFindByPk(RoleVO.class, vo.getRoleid());
		ArrayList list =(ArrayList)this.getService().doFindByProperty(RoleVO.class, "rolename", vo.getRolename());
		if(null != list && list.size()> 0){
			RoleVO newvo = (RoleVO)list.get(0);
			if(!newvo.getRolename().equals(oldVO.getRolename()))
			throw new Exception("角色名称已经存在");
		};
	}

	public String showroleofmenu() {
		try{
			paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
			String  roleId = (String)paramsMap.get("roleid");
			if(!StringUtils.isNotBlank(roleId)){
				return Action.SUCCESS;
			}
			paramsMap.put("treeXML", this.buildTreeXML(roleId));
			RoleVO roleVO = (RoleVO) this.getService().doFindByPk(voClass,new Long(roleId));
			this.setTargetObjectToParamsMap(roleVO, paramsMap);
				this.setIsEditAble(true);
				this.setIsNew(false);
			}catch(Exception ex){
				ex.printStackTrace();
				this.addErrorMessage(ex.getMessage());
				return Action.ERROR;
			}
		return Action.SUCCESS;
	}
	
	public String saveroleofmenu() {
		try{
			paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
			String selectMenus = (String) paramsMap.get("selectMenus");
			String roleId = (String) paramsMap.get("roleId");
			
			if(StringUtils.isNotBlank(selectMenus)){
				String []menuIds = selectMenus.split("\\|");
				//SaveRightStrategy strategy = new SaveRightStrategy(roleId, menuIds, userVO);
				SaveRoleOfMenuStrategy strategy = new SaveRoleOfMenuStrategy(new Long(roleId), menuIds, userVO);
				this.getService().doProcess(strategy);
			}
			
			if(StringUtils.isNotBlank(roleId)){
				paramsMap.put("treeXML", this.buildTreeXML(roleId));
				RoleVO roleVO = (RoleVO) this.getService().doFindByPk(voClass, PkUtils.getPkVO(voClass, pkNameArray, new String[]{roleId}));
				this.setTargetObjectToParamsMap(roleVO, paramsMap);
			}
			
			this.setIsEditAble(false);
			this.setIsNew(false);
		}catch(Exception ex){
			ex.printStackTrace();
			this.addErrorMessage(ex.getMessage());
			return Action.ERROR;
		}
		return Action.SUCCESS;
	}
	
	@SuppressWarnings("unchecked")
	private String buildTreeXML(String roleId) throws Exception {
		//QueryRightStrategy strategy = new QueryRightStrategy(roleId);
		QueryRoleOfMenuStrategy strategy = new QueryRoleOfMenuStrategy(roleId);
		List<MenuVO> menuList = (List<MenuVO>) this.getService().doProcess(strategy);
		StringBuffer treeBuff = TreeBuilder.buildTreeXML(menuList, "controlid", "lname", "pcontrolid", "controlid", "checked");
		return treeBuff.toString();
	}

	
	/**
	 * 
	* @Title: assign 
	* @Description: 赋权界面控制点JSON树生成
	* @param @return    设定文件 
	* @return String    返回类型 
	* @throws
	 */
	@SuppressWarnings("unchecked")
	public String getRoleMenuTree() {
		try {
			paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
			String roleId = (String) paramsMap.get("roleId");
			
			if(StringUtils.isNotBlank(roleId)){
				paramsMap.put("treeXML", this.buildTreeXML(roleId));
				RoleVO roleVO = (RoleVO) this.getService().doFindByPk(voClass, PkUtils.getPkVO(voClass, pkNameArray, new String[]{roleId}));
				this.setTargetObjectToParamsMap(roleVO, paramsMap);
			}
			QueryRoleOfMenuStrategy strategy = new QueryRoleOfMenuStrategy(roleId);
			List<MenuVO> menuList = (List<MenuVO>) this.getService().doProcess(strategy);
			List<TreeNode> treeList = new ArrayList<TreeNode>();
			for (MenuVO vo : menuList) {
				String menuid = vo.getControlid();
				String menuname = vo.getLname();
				String menupid = vo.getPcontrolid();

				TreeNode treeNode = new TreeNode();
				treeNode.setId(menuid);
				treeNode.setName(menuname);
				treeNode.setPId(menupid);
				treeNode.setChecked(vo.isChecked());
				treeNode.setOpen(true);
				treeList.add(treeNode);
			}
			sendJsonMessage(JsonUtils.toJson(treeList, null, true, null, false));
			return null;
		} catch (Exception ex) {
			ex.printStackTrace();
			this.addActionMessage(ex.getMessage());
			return Action.ERROR;
		}
	}
	/**
	 * 
	* @Title: assign 
	* @Description: 查询界面“赋权”操作
	* @param @return    设定文件 
	* @return String    返回类型 
	* @throws
	 */
	public String assign() {
		try {
			paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
			String  roleId = (String)paramsMap.get("roleId");
			if(!StringUtils.isNotBlank(roleId)){
				return Action.SUCCESS;
			}

			String selectMenus = (String) paramsMap.get("selectMenus");
			if(StringUtils.isNotBlank(selectMenus)){
				String []menuIds = selectMenus.split("\\|");
				SaveRoleOfMenuStrategy strategy = new SaveRoleOfMenuStrategy(new Long(roleId), menuIds, userVO);
				this.getService().doProcess(strategy);
				this.addMessage("修改成功");
			}
			
			RoleVO roleVO = (RoleVO) this.getService().doFindByPk(voClass,new Long(roleId));
			this.setTargetObjectToParamsMap(roleVO, paramsMap);
			this.setIsEditAble(false);
			this.setIsNew(false);
			paramsMap.put("roleId", roleId);
		} catch (Exception ex) {
			ex.printStackTrace();
			this.addErrorMessage(ex.getMessage());
			return Action.ERROR;
		}
		return Action.SUCCESS;
	}
	

	@Override
	protected void beforeList() throws Exception {
		 ((RoleListVO)this.getEntityListVO()).set_seq_comid(userVO.getComid());//公司权限控制
	}

	/**
	 * 新UI框架下的选择页面
	 * 
	 */
	public String select2() {
		try {
			RoleListVO listVO = new RoleListVO();
			paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
			this.setParamsMapToTargetObject(paramsMap, listVO);
			listVO.set_seq_comid(userVO.getComid());//公司权限控制
			beforeList();
			page = this.getService().doQuery(RoleVO.class, listVO);
		} catch (Exception ex) {
			this.addErrorMessage(ex.getMessage());
			return ERROR;
		}
		return SUCCESS;
	}
	
	/**
	 * 
	 * 删除角色
	 * 
	 * @Copyright: Copyright (c) 2006
	 * @Company: Revenco Tech Ltd.
	 * @anthor yixiaoping<yixiaoping@revenco.com>
	 * @since Nov 13, 2014 5:41:52 PM 
	 * @version V1.0
	 */
	@SuppressWarnings("unchecked")
    public String deleteRoleById(){
		JsonResult result = new JsonResult();
		try {
			paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
			String roleid = (String) paramsMap.get("roleid");
			Assert.notNull(roleid, "角色编码为空");	
			
			//查询角色否存在
			RoleVO roleVO = (RoleVO)this.getService().doFindByPk(RoleVO.class, Long.valueOf(roleid));
			Assert.notNull(roleVO, "角色不存在.角色编码:"+roleid);	
			
			//查询是否有有效的操作员关联角色
			String hql = "select ur from UserOfRoleVO ur ,UserVO u where ur.userid = u.userid and ur.roleid = ?";
			List<Object> list = (List<Object>)this.getService().doFindByHQL(hql, new Object[]{Long.valueOf(roleid)});
			if(list!=null && list.size()>0){
				result.setStatus("ERROR");
				result.setMessage("删除失败.存在操作员与该角色关联");
				sendJsonMessage(result);
				return null;
			}
			
			this.getService().doRemoveByPK(RoleVO.class, Long.valueOf(roleid));
			result.setStatus("OK");
			result.setMessage("删除成功");
			sendJsonMessage(result);
			return null;
		}catch (Exception e) {
			String errmsg = "删除车辆信息失败，失败原因：" + e.getMessage();
			log.error(errmsg, e);
			result.setStatus("ERROR");
			result.setMessage("异常:" + e.getMessage());
			try {
				sendJsonMessage(result);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			return null;
		}
	}

}
